package com.health.mapp.utils;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import net.sf.json.JSONObject;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import com.health.commons.PropertiesService;
 

public class HttpClientHelper {

	private static Log log = LogFactory.getLog(HttpClientHelper.class);

	@SuppressWarnings("deprecation")
	public static String sendPostHttp(String url, String message) {

		String s = "";
		if (null == message || "".equals(message)) {
			log.info("a blank message, return.");
			return "a blank message, return.";
		}
		log.info(message);
		HttpParams httpParameters = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);// 设置请求超时10秒
		HttpConnectionParams.setSoTimeout(httpParameters, 10 * 1000); // 设置等待数据超时10秒
		HttpConnectionParams.setSocketBufferSize(httpParameters, 8192);
		HttpConnectionParams.setSoKeepalive(httpParameters, true);

		HttpClient httpClient = new DefaultHttpClient(httpParameters); // 此时构造DefaultHttpClient时将参数传入

		HttpPost post = new HttpPost(url);

		StringEntity entity = new StringEntity(message, ContentType.create(
				"plain/text", Consts.UTF_8));

		post.setEntity(entity);

		int retry = 0;

		HttpResponse response = null;

		try {
			response = httpClient.execute(post);

			if (response.getStatusLine().getStatusCode() == 200) {
				log.debug("HttpStatus成功！");

				s = EntityUtils.toString(response.getEntity());
				s=new String(s.getBytes("ISO-8859-1"),"UTF-8");
				log.debug(s);
			} else {

				s = EntityUtils.toString(response.getEntity());

				log.debug(s);
				log.debug("HttpStatus失败！");
			}
		} catch (ClientProtocolException e) {
			String error=e.getMessage();
			s = "{\"retCode\":\"1004\",\"retInfo\":\""+error+"\"}";
			e.printStackTrace();
		} catch (ParseException e) {
			String error=e.getMessage();
			s = "{\"retCode\":\"1004\",\"retInfo\":\""+error+"\"}";
			e.printStackTrace();
		} catch (ConnectException e) {

			String error=e.getMessage();
			s = "{\"retCode\":\"1004\",\"retInfo\":\""+error+"\"}";
			e.printStackTrace();
		} catch (SocketTimeoutException e) {
			String error=e.getMessage();
			s = "{\"retCode\":\"1004\",\"retInfo\":\""+error+"\"}";
			e.printStackTrace();
		}
		catch (IOException e) {
			String error=e.getMessage();
			s = "{\"retCode\":\"1004\",\"retInfo\":\""+error+"\"}";
			e.printStackTrace();

		} catch (Exception e) {
			String error=e.getMessage();
			s = "{\"retCode\":\"1004\",\"retInfo\":\""+error+"\"}";
			e.printStackTrace();
		}
		return s;
	}
	
	@SuppressWarnings("deprecation")
	public static String sendGetHttp(String uriAPI, String message) {

		uriAPI = uriAPI +"?"+message;
		String result = "";
		// HttpGet httpRequst = new HttpGet(URI uri);
		// HttpGet httpRequst = new HttpGet(String uri);
		// 创建HttpGet或HttpPost对象，将要请求的URL通过构造方法传入HttpGet或HttpPost对象。
		HttpGet httpRequst = new HttpGet(uriAPI);

		try {
			// 使用DefaultHttpClient类的execute方法发送HTTP GET请求，并返回HttpResponse对象。
			HttpResponse httpResponse = new DefaultHttpClient()
					.execute(httpRequst);// 其中HttpGet是HttpUriRequst的子类
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity httpEntity = httpResponse.getEntity();
				result = EntityUtils.toString(httpEntity);// 取出应答字符串
				result=new String(result.getBytes("ISO-8859-1"),"UTF-8");
				// 一般来说都要删除多余的字符
				result.replaceAll("\r", "");// 去掉返回结果中的"\r"字符，否则会在结果字符串后面显示一个小方格
			} 
			else
			{
				httpRequst.abort();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = e.getMessage().toString();
		}

		return result;
	}

	
	
	public static void main(String[] args) throws NoSuchAlgorithmException {
		//String resString = sendPostHttp("http://www.bamboo-copter.cn/HiRoadAppInterface/servlet/Service", "appId=hiroad&version=4.0&method=queryRouteDetail&timestamp=20170622035214&uuId=ffffffff-dbbf-bfbc-ffff-fffff5f399ff&sign=A4664D3E3296EC4F7DC080A5F3E69BE2&lang=zh-hans&fill=00000000000000000000{\"memberId\":\"2017042500100045451\",\"routeId\":\"344\",\"flag\":\"0\"}");
	
		String user_phone = "13683293123";
		String atime = String.valueOf(DateUtils.millisSecond());
		String sign=getSign(atime,user_phone)  ;
		//1498637019
		//String param = "user_phone="+user_phone+"&atime="+atime+"&sign="+sign;
		
		String param = "user_phone="+user_phone+"&atime="+atime+"&sign="+sign+"&payment_id="+"-123457"
		+"&amount="+"8.88"+"&payment_flag="+"1"+"&partner="+"yihudaojia";
		System.out.println(param);
	/*	String retuenStr = sendGHttp("http://topen.yihu365.com/thirdInterface/payRecord.action",
				param);
		*/
		String retuenStr = sendPostHttp("http://topen.yihu365.com/thirdInterface/payRecord.action",
				param);
		if (retuenStr.contains("\"error_code\"")) {
			System.out.println("1");
		}else{
			System.out.println("2");
		}
		JSONObject jsStr = JSONObject.fromObject(retuenStr);
		String error_coder=jsStr.getString("error_code");
		
		if (StringUtils.isNotBlank(error_coder)&&("0".equals(error_coder))) {
			System.out.println(retuenStr+"><");
		}else{
			System.out.println(retuenStr+"<>");
		}
		
	}
	
    private  static String getSign( String atime, String user_phone) throws NoSuchAlgorithmException {

        //String partner_key = PropertiesService.getString("partnerKey").trim();  T00VRCuiyt7T2Bbz
    	String partner_key = "T00VRCuiyt7T2Bbz";
        String info = partner_key + atime + user_phone;
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] srcBytes = info.getBytes(); md5.update(srcBytes);
        byte[] resultBytes = md5.digest();
        String resultString = new String(new Hex().encode(resultBytes));
        return resultString.substring(8, 24);
    }
}
